package com.choosefine.it.worker.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.project.model.WorkerAttendanceDetail;
import com.choosefine.it.project.model.vo.WorkerSalaryChangeDetailsVO;
import com.choosefine.it.worker.dao.WorkerSalaryDayInterfaceMapper;
import com.choosefine.it.worker.model.WorkerSalaryDayInterface;
import com.choosefine.it.worker.model.vo.WorkerSalaryDayInterfaceVO;
import com.choosefine.it.worker.model.vo.WorkerSalaryMonthVO;

@Service("workerSalaryDayInterfaceService")
public class WorkerSalaryDayInterfaceService{
	
	Logger logger = LoggerFactory.getLogger(WorkerSalaryDayInterfaceService.class);
	
    @Autowired
    WorkerSalaryDayInterfaceMapper workerSalaryDayInterfaceMapper;
    @Autowired
    WorkerSalaryMonthService workerSalaryMonthService;
	
    /**
     * 11.26dzq 用于查出某团队下某时间段内的工人名单
     * @param map
     * @return
     */
    public List<Map<String, Object>> selectTeamMemberUserByTeamId(Map<String, Object> map){
    	return workerSalaryDayInterfaceMapper.selectTeamMemberUserByTeamId(map);
    }
    
	/**
     * 根据当前工人、所在班组关系、月份，查询月下的明细->天day
     * 
     * @auth liaozhanggen 2016-12-2 下午3:44:40
     */
   public List<WorkerSalaryDayInterface> queryWorkerSalaryDayDetails(WorkerSalaryDayInterface wsdi) throws BusinessException{
    	//校验传递参数的有效性
    	if (null == wsdi.getWorkerItemsRelationId() 
    			|| wsdi.getWorkerItemsRelationId().intValue() == 0
    			|| null == wsdi.getWorkerSalaryMonthId() 
    			|| wsdi.getWorkerSalaryMonthId().intValue() == 0
    			|| StringUtils.isEmpty(wsdi.getUserCode())) {
    		
			throw new BusinessException(ResultCode.MSG_ERROR, CommonConstant.TEAM_RECRUITMENT_ID_IS_NULL);
		}
    	Map<String,Object> map = new HashMap<>();
    	map.put("workerItemsRelationId", wsdi.getWorkerItemsRelationId());
    	map.put("workerSalaryMonthId", wsdi.getWorkerSalaryMonthId());
    	map.put("userCode", wsdi.getUserCode());
    	return workerSalaryDayInterfaceMapper.queryWorkerSalaryDayDetails(map);
    }
   
   /**
    * 添加职工考勤记录 单个/批量
    * @throws Exception 
    * 
    * @auth liaozhanggen 2016-12-12 下午5:20:36
    */
   public int insertWorkerAttendanceRecord(List<WorkerAttendanceDetail> record) throws Exception{
	   List<Integer> arr = null;
	   List<WorkerSalaryDayInterface> wsdiList = null;
		try {
			wsdiList = dataOrgTransfer(record);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(ResultCode.FAILED,e.getMessage());
		}
	   int num = null != wsdiList && wsdiList.size() > 0 ? workerSalaryDayInterfaceMapper.insertWorkerAttendanceRecord(wsdiList) : 0;
	   
	   if (num > 0) {
		   arr = new ArrayList<Integer>();
		   for (WorkerSalaryDayInterface wsdi : wsdiList) { //根据添加的记录的id，然后去同步数据到正式表中
			  arr.add(wsdi.getId());
			  logger.info("----arr------>" + wsdi.getId());
		   }
		   
		   num = workerSalaryDayInterfaceMapper.addSyncWorkerAttendanceInterfaceRecord(arr);
		   syncAddtendanceDataByUserCode(record);
	   }
	   return num;
   }
 
	/** 
	 * 同步实时计算当前用户考勤信息
	 * @throws BusinessException 
	 * @Author：liaozhanggen
	 * @Create Date：2017年2月25日
	 * @param：....
	 * @return：void
	 */
   @Transactional(propagation=Propagation.REQUIRES_NEW)
	private void syncAddtendanceDataByUserCode(List<WorkerAttendanceDetail> record) throws BusinessException {
		//修改考勤信息
	   try {
		Map<String, String> param = null;
		   for (WorkerAttendanceDetail wad : record) {
			   param = new HashMap<>();
			   param.put("message", "start");
			   param.put("userCode", wad.getUserCode());
			   param.put("currentDate", wad.getDataTime().substring(0, 7));
			   String message = workerSalaryMonthService.saveWorkerSalaryCurrentMonthCalc(param);
			   if (ResultCode.MSG_SUCCESS.equalsIgnoreCase(param.get("message"))) {
					logger.info("-----syncAddtendanceDataByUserCode------>" + param.get("message") + "," + message );
				}
			   param = null;
		   }
	} catch (Exception e) {
		e.printStackTrace();
		throw new BusinessException(ResultCode.FAILED, CommonConstant.DATA_SYNC_ERROR);
	}
	}

	private List<WorkerSalaryDayInterface> dataOrgTransfer(List<WorkerAttendanceDetail> record) throws Exception {
		List<WorkerSalaryDayInterface> wsdiList = null;
		if (record.size() > 0) {
			   wsdiList = new ArrayList<WorkerSalaryDayInterface>();
			   for (WorkerAttendanceDetail wad : record) {
				   checkIsExistsWorkerAttendance(wad); // 校验数据是否已经存在 2017-01-06
				   WorkerSalaryDayInterface wsdi = new WorkerSalaryDayInterface();
				   wsdi.setUserCode(wad.getUserCode());
				   wsdi.setTeamId(wad.getTeamId());
				   wsdi.setProjectCode(wad.getProjectCode());
				   wsdi.setWorkTimeStart(DateUtils.getFomartToDate(wad.getDataTime().trim().concat(" "+wad.getOrgWorkTimeStart().trim())).getTime());
				   wsdi.setWorkTimeEnd(DateUtils.getFomartToDate(wad.getDataTime().trim().concat(" "+wad.getOrgWorkTimeEnd().trim())).getTime());
				   wsdi.setWorkTime(wad.getWorkTime());
				   wsdi.setUnitSalary(wad.getUnitSalary());
				   wsdi.setWorkTimeChanged(wad.getChgWorkTimeAdjust());
				   wsdi.setChangedSalary(null!=wad.getActualSalary() ? wad.getActualSalary() : wad.getChgWorkTimeAdjust().multiply(wad.getUnitSalary()));
				   wsdi.setChangedReason(wad.getChangeReason());
				   wsdiList.add(wsdi);
			   }
		   }
		return wsdiList;
	}
	
	/**
	 * 校验根据project_code,team_id,user_code,worker_time_start 四个参数校验当前职员是否已经存在考勤worker_time_start
	 * 
	 * @author liaozhanggen 2017年1月6日
	 * @throws BusinessException 
	 */
	private void checkIsExistsWorkerAttendance(WorkerAttendanceDetail wad) throws BusinessException{
		Map<String,Object> param = new HashMap<>();
		param.put("projectCode", wad.getProjectCode());
		param.put("teamId", wad.getTeamId());
		param.put("userCode", wad.getUserCode());
		param.put("dataTime", wad.getDataTime());
		int count = workerSalaryDayInterfaceMapper.queryIsExistsWorkerAttendance(param);
		if (count > 0) {
			throw new BusinessException(ResultCode.FAILED, String.format(CommonConstant.DATE_IS_EXISTS_SYSTEM, wad.getDataTime()));
		}
	}

   /**
    * 编辑职工考勤记录-批量/单个
    * @throws Exception 
    * 
    * @auth liaozhanggen 2016-12-13 上午11:04:31
    */
	public int editWorkerAttendanceRecord(List<WorkerAttendanceDetail> record) throws Exception {
		List<WorkerSalaryDayInterface> wsdiList = null;
		try {
			wsdiList = dataChgTransfer(record);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(ResultCode.FAILED,e.getMessage());
		}
		int num =  null != wsdiList && wsdiList.size() > 0 ? workerSalaryDayInterfaceMapper.updateBatchWorkerAttendanceRecords(wsdiList) : 0;
		if (num > 0) {
			syncAddtendanceDataByUserCode(record);
		}
		return num;
	}

	private List<WorkerSalaryDayInterface> dataChgTransfer(List<WorkerAttendanceDetail> record) throws Exception {
		List<WorkerSalaryDayInterface> wsdiList = null;
		if (record.size() > 0) {
			   wsdiList = new ArrayList<WorkerSalaryDayInterface>();
			   for (WorkerAttendanceDetail wad : record) {
				   WorkerSalaryDayInterface wsdi = new WorkerSalaryDayInterface();
				   wsdi.setUserCode(wad.getUserCode());
				   wsdi.setTeamId(wad.getTeamId());
				   wsdi.setProjectCode(wad.getProjectCode());
				   wsdi.setWorkTimeStart(DateUtils.getFomartToDate(wad.getDataTime().trim().concat(" "+wad.getChgWorkTimeStart().trim())).getTime());
				   wsdi.setWorkTimeEnd(DateUtils.getFomartToDate(wad.getDataTime().trim().concat(" "+wad.getChgWorkTimeEnd().trim())).getTime());
				  if(!wad.getChgWorkTime().equals(BigDecimal.ZERO)){
				    wsdi.setWorkTime(wad.getChgWorkTime());
				  }//调整后的工数yuxin
				   if(!wad.getUnitSalary().equals(BigDecimal.ZERO)){
				   wsdi.setUnitSalary(wad.getUnitSalary());
				  }//调整后的工价yuxin
				   wsdi.setWorkTimeChanged(wad.getChgWorkTimeAdjust());
				   wsdi.setChangedSalary(null != wad.getActualSalary() ? wad.getActualSalary() : wad.getChgWorkTimeAdjust().multiply(wad.getUnitSalary()));
				   wsdi.setChangedReason(wad.getChangeReason());
				   wsdi.setPriceChangeReason(wad.getPriceChangeReason());
				   wsdi.setOperatorNum(wad.getOperatorNum());
				   wsdi.setId(wad.getId());
				   wsdiList.add(wsdi);
			   }
		   }
		return wsdiList;
	}
	
	 /**
     * 工人开始工作最小时间
     * @param map
     * @return
     */
   public long selectMinTime(Map<String, Object> map){
	   return workerSalaryDayInterfaceMapper.selectMinTime(map);
   }

	/**
	 * 根据每月查看每天的考勤详情,不用分页
	 * 
	 * @author liaozhanggen 2016年12月29日
	 */
	public WorkerSalaryMonthVO selectDaySalaryDetailByMonthly(Map<String, Object> map) {
		List<WorkerSalaryDayInterfaceVO> record = workerSalaryDayInterfaceMapper.selectDaySalaryDetailByMonthly(map);
		for (WorkerSalaryDayInterfaceVO wsdivo : record) {
			wsdivo.setActualSalary(wsdivo.getUnitSalary().multiply(wsdivo.getWorkTime()));
		}
		
		WorkerSalaryMonthVO monthTotal = workerSalaryDayInterfaceMapper.selectmonthtotal(map);
		if (monthTotal != null) {
			monthTotal.setWorkerSalaryDayInterfaceVOS(record);
			monthTotal.setUnpaidMoney(monthTotal.getReceivableMoney().subtract(monthTotal.getReceivedMoney()));
		}
		return monthTotal;
	};
/** 
 * @Description：项目管理-班组资金管理-工人工资管理-工人工资明细-8082月份列表
 * @Author：yuxin
 * @Create Date：2017/2/25/0025
 * @param：
 * @return：
 */
	public WorkerSalaryMonthVO selectmonthlist(Map<String, Object> map) {
		Map monthTotal=workerSalaryDayInterfaceMapper.selectmonthlisttotal(map);
		WorkerSalaryMonthVO wVO=new WorkerSalaryMonthVO();
		if(monthTotal!=null) {
			/*wVO.setWorkerSalaryDayInterfaceVOS(wsdivos);*/
			wVO.setTotalWorkTime((BigDecimal) monthTotal.get("work_time"));
			wVO.setReceivableMoney((BigDecimal) monthTotal.get("receivable_money"));
			wVO.setReceivedMoney((BigDecimal) monthTotal.get("received_money"));
			wVO.setUnpaidMoney(wVO.getReceivableMoney().subtract(wVO.getReceivedMoney()));
		}
		return wVO;
	};

	/**
	 * 单个工人薪资工资明细
	 * 
	 * @throws BusinessException 
	 * 
	 * @Author：liaozhanggen
	 * @Create Date：2017年2月25日
	 * @param：....
	 * @return：WorkerSalaryChangeDetailsVO
	 */
	public WorkerSalaryChangeDetailsVO findWorkerSalaryDayDetail(int id) throws BusinessException{
		if (id <= 0) {
			throw new BusinessException(ResultCode.FAILED, CommonConstant.PARAMETER_ERROR);
		}
		
		WorkerSalaryChangeDetailsVO details = workerSalaryDayInterfaceMapper.selectWorkerSalaryDayDetail(id);
		if(details!=null){
			details.setDataTime(details.getChgWorkTimeStart());
		}
		return details;
	}

	/**
	 * 失效 指定哪条工人的哪天考勤
	 * 
	 * @auth liaozhanggen 2016-12-10 下午7:58:36
	 */
	public int modifyWorkerAttendInvalid(String workerSalaryDayInterfaceId) throws BusinessException {

		if (null == workerSalaryDayInterfaceId || "".equals(workerSalaryDayInterfaceId.trim())) {
			throw new BusinessException(ResultCode.FAILED, CommonConstant.TEAM_RECRUITMENT_ID_IS_NULL);
		}
		List<String> wsdfIds = Arrays.asList(workerSalaryDayInterfaceId.split(","));
		try {
			for (String wsdfId : wsdfIds) {
				Integer.valueOf(wsdfId);
			}
		} catch (NumberFormatException e) {
			throw new BusinessException(ResultCode.FAILED, CommonConstant.TEAM_RECRUITMENT_ID_IS_NULL);
		}
		int num = workerSalaryDayInterfaceMapper.modifyWorkerAttendInvalid(wsdfIds);
		if (num > 0) {
			List<WorkerAttendanceDetail> record = workerSalaryDayInterfaceMapper.findWorkAttendByListID(wsdfIds);
			syncAddtendanceDataByUserCode(record);
		}
		return num;
	}
}
